package 树;

/**
 * @author ssh
 * @date 2025/8/24
 * @description
 */
public class 对称二叉树 {


    public boolean isSymmetric(TreeNode root) {

        return check(root.left, root.right);
    }

    public boolean check(TreeNode p, TreeNode q) {
        //判断是不是只有根节点
        if (p == null && q == null) {
            return true;
        }
        //只有左子树或者只有右子树
        if (p == null || q == null) {
            return false;
        }
        //判断同一层的（非）叶子节点是不是相等，如果不相等，就没有往下比较的必要了
        if (p.val != q.val) {
            return false;
        }
        return check(p.left, q.right) && check(p.right, q.left);
    }
    public static void main(String[] args) {
        // 测试代码
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(2);
        root.left.left = new TreeNode(3);
        root.left.right = new TreeNode(4);
        root.right.left = new TreeNode(4);
        root.right.right = new TreeNode(3);

        对称二叉树 solution = new 对称二叉树();
        boolean result = solution.isSymmetric(root);
        System.out.println(result); // 输出: true
    }
}
